<?php

class Dispatcher {
	
	public static function dispatch() {
		$request = self::_loadRequest();
		
		$className = file2class($request["controller"]);
		
		$ctrl = new $className();
		$ctrl->request = (Object)$request;
		
		if(method_exists($ctrl, $request["action"])) {
			$ctrl->init();
			$params = $request["params"] ? '"' . implode('","', $request["params"]) . '"' : "";
			$toeval = '$ctrl->' . $request["action"] . "($params);";
			eval($toeval);
			if($ctrl->autoRender) {
				$ctrl->render();
			}
		}else{
			die("Class <i>$className</i> doesn't know for <i>".$request["action"] . "</i> action");
		}
	}
	
	private static function _loadRequest() {
		$r = preg_split('/\//', $_GET["request"], -1, PREG_SPLIT_NO_EMPTY);
		$named = array();
		foreach($r as $k=>$v) {
			if(strstr($v, ";")) {
				list($name, $value) = explode(";", $v, 2);
				$named[$name] = $value;
				unset($r[$k]);
			}
		}
		$r = array_values($r);
		$controller = array_shift($r);
		$action = array_shift($r);
		
		return array(
			"named" => $named,
			"controller" => $controller ? $controller : DEFAULT_CONTROLLER,
			"action" => $action ? $action : DEFAULT_ACTION,
			"params" => $r
		);
	}
}

?>